package com.jeady.jTools.imitateChat

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.media.Image
import android.media.MediaPlayer
import android.net.Uri
import android.opengl.Visibility
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
import com.jeady.jTools.R
import com.jeady.jTools.feedback.FeedbackActivity
import java.util.*
import kotlin.collections.ArrayList


class ImitateWechatActivity: AppCompatActivity() {

    val TAG = "imitate wechat"
    // 消息列表
    lateinit var msgContainer: LinearLayout
    // 消息列表的滚动视图
    lateinit var svContainer: ScrollView
    // 定义默认头像为空
    var objAvatorUri: Uri = Uri.EMPTY
    var myAvatorUri: Uri = Uri.EMPTY
    // 消息配置Dialog
    lateinit var chatConfigDialog: ChatConfigDialog
    // 消息列表
    lateinit var msgList: ArrayList<String>
    // 遍历消息列表用到的索引值, 用于全自动消息处理
    var indexMsg = 0
    // 除消息头外消息正式开始的位置索引
    val msgStartIndex = 5
    // 消息声音
    lateinit var mpMsg: MediaPlayer
    // 输入框组件
    lateinit var etMsg: EditText
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_0wechat)

        etMsg = findViewById<EditText>(R.id.et_msg)

        msgList = ArrayList()
        mpMsg = MediaPlayer.create(baseContext, R.raw.voice_bubble)

        svContainer = findViewById(R.id.sv_msg_list)
        // 消息列表容器
        msgContainer = findViewById(R.id.vll_msg_container)
        // 处理右上角配置消息按钮
        findViewById<ImageView>(R.id.iv_btn_chat_config).setOnClickListener {
            chatConfigDialog.setOwnerActivity(this)
            chatConfigDialog.show()
        }
        // 用于添加消息的 TimerTask, 参数once指示是否只发送一条
        class TskAddMsg(index: Int, once: Boolean = true): TimerTask(){
            val bOneMsg = once
            val iIndex = index
            override fun run() {
                val hMsg = Message()
                val msg: String
                try {
                    if(bOneMsg){
                        msg = msgList[iIndex]
                    }else {
                        msg = msgList[indexMsg]
                    }
                }catch (e: IndexOutOfBoundsException){
                    this.cancel()
                    return
                }
                hMsg.what = 300
                hMsg.obj = msg.substring(msgStartIndex)
                hMsg.arg1 = msg.substring(0..0).toInt()
                handler.sendMessage(hMsg)
                if(bOneMsg){
                    this.cancel()
                }else{
                    ++indexMsg
                }
            }
        }
        // 配置消息记录的dialog
        class OnChatConfigFinish : ChatConfigDialog.OnClickFinish {
            override fun handleData(data: Bundle) {
                Log.e(
                    TAG, "handleData: handle finished , " +
                            "his nickname = ${data.get("objName")}" +
                            "my nickname = ${data.get("myName")}" +
                            "get msgList ${data.get("msgList")}\n" +
                            "$baseContext"
                )
                // 设置聊天页面顶部标题
                findViewById<TextView>(R.id.tv_chat_objName).text = data.getString("objName")
                // 获取配置好的消息列表
                msgList = data.getStringArrayList("msgList")!!
                msgContainer.removeAllViews()
                // 判断如果是静态页面，则立即进行处理； 否则进行动态处理
                val chatType = data.getInt("msgType")
                if(chatType == 0){  // 静态消息页面
                    Log.d(TAG, "handleData: 静态消息处理")
                    for (msg in msgList) {
                        if (msg.startsWith("0")) {
                            addMsg(baseContext, msg.substring(msgStartIndex))
                        } else {
                            addMsg(baseContext, msg.substring(msgStartIndex), 1)
                        }
                    }
                } else if(chatType == 1){    // 半自动消息页面
                    Log.d(TAG, "handleData: 半自动消息处理")
                    val timer = Timer()
                    var tsk: TskAddMsg
                    var timeDelay = 0
                    var tempDelay = 0
                    indexMsg = 0
                    for(msg in msgList){
                        if(msg[0] == '0'){
                            Log.e(TAG, "handleData: indexMsg 值1为 $indexMsg", )
                            tsk = TskAddMsg(indexMsg++)
                            Log.e(TAG, "handleData: indexMsg 值2为 $indexMsg", )
                            when(msg[1]){
                                '0' -> tempDelay = 1
                                '1' -> tempDelay = 3
                                '2' -> tempDelay = 5
                                '3' -> tempDelay = 10
                            }
                            timeDelay += tempDelay
                            Log.e(TAG, "handleData: 启动定时器 $timeDelay 秒" )
                            timer.schedule(tsk, (timeDelay * 1000).toLong(), 1000)
                        }else{
                            val cb = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                            val cbData = ClipData.newPlainText("next_msg", msg)
                            cb.setPrimaryClip(cbData)
                            break
                        }
                    }
                } else {        //全自动消息页面
                    Log.d(TAG, "handleData: 全自动消息处理")
                    val timer = Timer()
                    val tsk = TskAddMsg(0,false)
                    var timeDelay = 3
                    when(chatType - 2){
                        0 -> timeDelay = 1
                        1 -> timeDelay = 2
                        2 -> timeDelay = 3
                        3 -> timeDelay = 5
                    }
                    timeDelay *= 1000
                    Log.e(TAG, "handleData: timeDelay = $timeDelay", )
                    indexMsg = 0
                    timer.schedule(tsk, timeDelay.toLong(), timeDelay.toLong())
                }
            }
        }

        // 打开或关闭底部附加功能
        val ivShowAddtion = findViewById<ImageView>(R.id.iv_show_addition)
        val addtionArea = findViewById<LinearLayout>(R.id.hll_addition_area)
        ivShowAddtion.setOnClickListener{
            if (addtionArea.visibility == View.GONE){
                addtionArea.visibility = View.VISIBLE
                ivShowAddtion.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_add2, null))
            }else{
                addtionArea.visibility = View.GONE
                ivShowAddtion.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_add, null))
            }
        }

        val onConfigFinish = OnChatConfigFinish()
        chatConfigDialog = ChatConfigDialog(this, onConfigFinish)
        // 处理发送来自对方的消息按钮
        (findViewById<Button>(R.id.btn_msg_from)).setOnClickListener {
            addMsg(it.context, etMsg.text.toString())
            etMsg.setText("")
        }

        // 处理发送来自自己的消息按钮
        findViewById<Button>(R.id.btn_msg_to).setOnClickListener {
            addMsg(it.context, etMsg.text.toString(), 1)
            etMsg.setText("")
        }

        // 处理反馈按钮
        findViewById<Button>(R.id.btn_chat_feedback).setOnClickListener {
            val fdActivity = Intent(this, FeedbackActivity::class.java)
            startActivity(fdActivity)
        }

        //        svContainer.fullScroll(View.FOCUS_DOWN)
        // 监听消息输入框的变化， 用于控制发送的按钮的显示与隐藏
        class TW : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                val btnSend = findViewById<TextView>(R.id.btn_send_msg)
                val btnAnother = findViewById<ImageView>(R.id.iv_show_addition)
                if (s.toString().isNotEmpty()) {
                    btnSend.visibility = View.VISIBLE
                    btnAnother.visibility = View.GONE
                } else {
                    btnSend.visibility = View.GONE
                    btnAnother.visibility = View.VISIBLE
                }
            }
        }

        // 设置消息输入框的文本改变
        etMsg.addTextChangedListener(TW())

        // 监听发送消息按钮
        findViewById<TextView>(R.id.btn_send_msg).setOnClickListener() {
            addMsg(it.context, etMsg.text.toString(), 1)
            etMsg.setText("")
            etMsg.post{
                etMsg.requestFocus()
            }
            ++indexMsg
            Log.e(TAG, "onCreate: 已自增索引值 $indexMsg ")
            if(msgList.size > indexMsg){
                Log.e(TAG, "onCreate: 已自增索引值 $indexMsg ${msgList.size}")
                val timer = Timer()
                var tsk: TskAddMsg
                var timeDelay = 0
                var tempDelay = 0
                for(msg in msgList.subList(indexMsg, msgList.size)){
                    if(msg[0] == '0'){
                        tsk = TskAddMsg(indexMsg)
                        when(msg[1]){
                            '0' -> tempDelay = 1
                            '1' -> tempDelay = 3
                            '2' -> tempDelay = 5
                            '3' -> tempDelay = 10
                        }
                        timeDelay += tempDelay
                        timer.schedule(tsk, (timeDelay * 1000).toLong(), 1000)
                        ++indexMsg
                    }else{
                        val cb = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                        val cbData = ClipData.newPlainText("next_msg", msg.substring(msgStartIndex))
                        cb.setPrimaryClip(cbData)
                        break
                    }
                }
            }
        }
    }

    // 添加消息框
    fun addMsg(context: Context, msg: String, direction: Int = 0){
        Log.e(TAG, "onCreate: drection=$direction, add msg=$msg")
        if(msg.isBlank()) {
            return
        }
        // 播放气泡音效
        Thread {
            mpMsg.start()
        }.start()

        val msgArea = LinearLayout(context)
        msgArea.orientation = LinearLayout.HORIZONTAL

        // 添加头像显示
        Log.e(TAG, "addMsg: add avtor show and set width and height")
        val msgAvator = ImageView(context)
        if(direction == 0){
            if(objAvatorUri != Uri.EMPTY) {
                msgAvator.setImageURI(objAvatorUri)
            }else{
                msgAvator.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_icon, null))
            }
        }
        if(direction == 1){
            if(myAvatorUri != Uri.EMPTY) {
                msgAvator.setImageURI(myAvatorUri)
            }else{
                msgAvator.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_icon, null))
            }

        }
        val lp = LinearLayout.LayoutParams(80, 80)

        val msgTv = JTextView(context, direction)
        msgTv.text = msg
        if(direction == 0) {
            msgArea.addView(msgAvator)
            msgArea.addView(msgTv)
            msgArea.gravity = Gravity.START
            lp.marginEnd = 10
        }else{
            msgArea.addView(msgTv)
            msgArea.addView(msgAvator)
            msgArea.gravity = Gravity.END
            lp.marginStart = 10
        }
        msgAvator.layoutParams = lp
        msgContainer.addView(msgArea)

        svContainer.post {
            svContainer.fullScroll(View.FOCUS_DOWN)
        }

    }
    val handler = Handler(Looper.myLooper()!!){
        when(it.what){
            300 -> {
                addMsg(baseContext, it.obj.toString(), it.arg1)
            }
        }
        return@Handler true
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 1001){
            try{
                objAvatorUri = data?.data!!
                chatConfigDialog.setAvator(objAvatorUri, 0)
            }catch (e: NullPointerException){
            }
    }else if(requestCode == 1002){
            try {
                myAvatorUri = data?.data!!
                chatConfigDialog.setAvator(myAvatorUri, 1)
            }catch (e: NullPointerException){
            }
        }
    }
}